package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.math.BigDecimal;

import static com.shanxia.codec.CodeConstant.HUNDRED;
import static com.shanxia.codec.CodeConstant.PERCENT;
import static com.shanxia.codec.Decoder.*;

/**
 * S -> C
 * 服务器应答充电密码验证报文
 */
@Data
public class Cmd205 extends ProtocolDataBase {

    public static final int MIN_SIZE = 12;

    private int v1;                     // 预留
    private int v2;                     // 预留
    private int respCode;               // 响应码
    private double balance;             // 账户余额

    public Cmd205(){
        super.setCmd(205);
    }

    public static Cmd205 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd205 cmd = new Cmd205();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        //数据域长度
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 4字节响应码
        cmd.respCode = getInt32(dataField, offset);
        offset += 4;
        // 4字节用户余额
        cmd.balance = new BigDecimal(getInt32(dataField, offset)).multiply(PERCENT).doubleValue();
        return cmd;
    }

    @Override
    public byte[] getDataField() {
        byte[] data = new byte[MIN_SIZE];
        getBytesAsUint16(data, 0, this.v1);
        getBytesAsUint16(data, 2, this.v2);
        // 4字节响应码
        intToBytesLittle(data, 4, this.respCode);
        // 4字节账户余额
        intToBytesLittle(data, 8, new BigDecimal(String.valueOf(balance)).multiply(HUNDRED).intValue());
        return data;
    }
}
